package top.zymall.sms.sms;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import top.zymall.sms.properties.SmsProperties;

import javax.swing.text.html.FormSubmitEvent;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 10:41 2019/7/11
 */
@Slf4j
@Component
@EnableConfigurationProperties(value = SmsProperties.class)
public class SmsUtil {

    @Autowired
    private SmsProperties smsProperties;

    /****
     * 发送阿里短信
     * @param mobile
     */
    public String sendAliSms(String mobile,String templateCode,String templateParam){
        DefaultProfile profile = DefaultProfile.getProfile("default", smsProperties.getAccessKeyId(), smsProperties.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", smsProperties.getSignName());
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject jsonObject = JSONObject.parseObject(response.getData());
            String responseCode=jsonObject.getString("Code");
            String responseMessage=jsonObject.getString("Message");
            if (!"OK".equals(responseCode)){
                log.info("[短信服务]发送短信失败，手机号:{},原因:{}",mobile,responseMessage);
            }
            return responseCode;
        } catch (Exception e) {
            log.error("[短信服务]发送短信异常，手机号:{}",mobile,e);
            return null;
        }
    }
}
